#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import logging

from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext import db
from geo.geomodel import GeoModel

# geospatial queries - http://code.google.com/apis/maps/articles/geospatial.html
class User(GeoModel):
	email = db.StringProperty()
	tasteSig = db.StringProperty()
	artists = db.StringListProperty()

class Session(db.Model):
    email = db.StringProperty()
    alreadyPlayed = db.StringListProperty()
    currentlyPlaying = db.StringProperty()

class MainHandler(webapp.RequestHandler):
    def get(self):
        self.response.out.write('Hello world???')

class CheckinHandler(webapp.RequestHandler):
    def get(self):
		lat = self.request.get("lat")
		lng = self.request.get("lng")
		tasteSig = self.request.get("tasteSig")
		email = self.request.get("email")

        # do I have this already?

		userQuery = db.GqlQuery("SELECT * FROM User WHERE email = :1 and tasteSig = :2", email, tasteSig)
		res = userQuery.fetch(1)
		
		if len(res) > 0:
			# update the users lat & lng
			user = res[0]
			user.location = db.GeoPt(lat,lng)
			user.update_location()
			user.put()
			self.response.out.write('OK')
		else:
			self.response.out.write('checkin.add')

class CheckinAddHandler(webapp.RequestHandler):
    def get(self):
		email = self.request.get("email")
		artists = self.request.get("artists").split(",")
		tasteSig = self.request.get("tasteSig")
		lng	= self.request.get("lng")
		lat = self.request.get("lat")

        # update artistlist property for user
		currUserQuery = db.GqlQuery("SELECT * FROM User WHERE email = :1", email)
		currUser = currUserQuery.fetch(0)
		if not currUser:
			currUser = User()
			currUser.email = email
	
		currUser.artists = artists
		currUser.tasteSig = tasteSig
		currUser.location = db.GeoPt(lat,lng)
		currUser.update_location()
		currUser.email = email
		
		logging.info('storing user %s', currUser)

        # pop the user into the db
		currUser.put();
		self.response.out.write('OK')
        
class QueryHandler(webapp.RequestHandler):
    def get(self):
		email = self.request.get("email")
		lat = self.request.get("lat")
		lng = self.request.get("lng")
		radius = self.request.get("radius")
    
        # update users lat / lng
		userQuery = db.GqlQuery("SELECT * from User where email = :1",email)
		results = userQuery.fetch(1)
		
		if len(results) <= 0:
			self.response.out.write('USER NOT FOUND')
			return
			
		currUser = results[0]
		currUser.location = db.GeoPt(lat,lng)
		currUser.update_location()

        # perform geo spatial query
		userQuery = User.all()
		logging.info('querying with center (%s,%s)',lat,lng)
		results = User.proximity_fetch(userQuery, db.GeoPt(lat,lng), max_results=1000, max_distance=radius)
		
		for user in results:
			logging.info('found user %s', user)
        
        # merge artist lists from users
        
        # subtract any songs from alreadyPlayed
        
        # create / update session

		self.response.out.write('QUERY')
		

def main():
    application = webapp.WSGIApplication([('/', MainHandler),
                                          ('/checkin', CheckinHandler),
                                          ('/checkin.add', CheckinAddHandler),
                                          ('/query', QueryHandler)] ,
                                         debug=True)
    util.run_wsgi_app(application)

if __name__ == '__main__':
    main()
